//
//  UIColor+MKSAdd.swift
//  MeetCarefree
//
//  Created by MK on 2021/6/10.
//  Copyright © 2021 xxf. All rights reserved.
//

import Foundation
import UIKit

extension UIColor {
    @objc public convenience init(hexRGB: UInt, alpha: CGFloat = 1.0){
        self.init(
            red: CGFloat((hexRGB & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((hexRGB & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(hexRGB & 0x0000FF) / 255.0,
            alpha: alpha)
    }
    
    @objc public convenience init(R r:CGFloat, G g:CGFloat, B b:CGFloat, A a:CGFloat = 1.0){
        self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
    }
    
//    @objc public convenience init(rgbString: String?){
//        if let str = rgbString {
//            if str.hasPrefix("#"){
//                let hex = str.sub
//            }
//        }
//    }
    
    @objc public convenience init?(rgbString: String?, separatorBy separator:String = ","){
        if let rgb = rgbString {
            let strAry = rgb.components(separatedBy: separator)
            if strAry.isEmpty || strAry.count < 3 {
                return nil
            }
            
            var floatAry = [CGFloat]()
            for s in strAry {
                if let t = Double(s){
                    floatAry.append(CGFloat(t))
                }else{
                    return nil
                }
            }
            
            if floatAry.count == 3 {
                self.init(R: floatAry[0], G: floatAry[1], B: floatAry[2])
                return
            }else if floatAry.count == 4 {
                self.init(R: floatAry[0], G: floatAry[1], B: floatAry[2], A: floatAry[3])
                return
            }
        }
        return nil
    }
}
